package com.geostar.constructionland.attachment.util;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * <HttpServletResponse帮助类>
 * 
 * @author  wanqing
 * @version  [版本号, 2016年8月5日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
@Slf4j
public class ResponseUtils {
    
    /**
     * 发送文本。使用UTF-8编码。
     * 
     * @param response
     *            HttpServletResponse
     * @param text
     *            发送的字符串
     */
    public static void renderText(HttpServletResponse response, String text) {
        render(response, "text/plain;charset=UTF-8", text);
    }

    /**
     * 发送json。使用UTF-8编码。
     * 
     * @param response
     *            HttpServletResponse
     * @param text
     *            发送的字符串
     */
    public static void renderJson(HttpServletResponse response, String text) {
        render(response, "application/json;charset=UTF-8", text);
    }
    
    /**
     * 发送json。使用UTF-8编码。并且判断是否需要支持跨域调用
     * @param request
     * @param response
     * @param text [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static void renderJson(HttpServletRequest request,HttpServletResponse response, String text) {
        String callback = request.getParameter("callback");
        //如果不传输callback，不支持跨域调用，否则支持跨域调用。
        if(StringUtils.isNotBlank(callback)){
            render(response, "application/json;charset=UTF-8", callback+"("+text+")");
        }else{
            render(response, "application/json;charset=UTF-8",text);
        }
    }

    /**
     * 发送xml。使用UTF-8编码。
     * 
     * @param response
     *            HttpServletResponse
     * @param text
     *            发送的字符串
     */
    public static void renderXml(HttpServletResponse response, String text) {
        render(response, "text/xml;charset=UTF-8", text);
    }
    
    /**
     * 发送内容。使用UTF-8编码。
     * 
     * @param response
     * @param contentType
     * @param text
     */
    public static void render(HttpServletResponse response, String contentType,
            String text) {
        response.setContentType(contentType);
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        if(text != null){
            try {
                response.getWriter().write(text);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
    
}
